import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select, message
} from 'antd'
import {useState, useRef, useEffect} from 'react'
import { PlusOutlined } from '@ant-design/icons'
import {Link, useNavigate, useSearchParams} from 'react-router-dom'
import {useStore} from '@/store'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import {observer} from "mobx-react-lite";
import {http} from "@/utils";

const { Option } = Select

const Publish = () => {
  const navigate=useNavigate();
  const formRef=useRef();
  const [params]=useSearchParams();
  const id=params.get('id');

  const fileListRef=useRef([]);

  console.log('渲染了')
const {channelStore}=useStore();
const [fileList,setFileList]=useState([])
  const [imgCount,setImgCount]=useState(1);
useEffect(()=>{
   channelStore.loadChannelList()
},[])
const onUploadChange=(res)=>{
  console.log(res,'res')
  // if(res.fileList[0].status==='done'){
  //   setFileList(res.fileList);
  // }
  const formatList=res.fileList.map(file=>{
     if(file.response){
        return {
          url:file.response.data.url
        }
     }
     return  file
  })
  setFileList(formatList);
  fileListRef.current=res.fileList;
  // console.log(res.fileList,'22222222222222');
  // console.log(fileListRef,'33333333333');

}
const radioChange=(e)=>{
  console.log(e.target.value)
  setImgCount(e.target.value*1)
  if(e.target.value===1){
    // console.log(fileListRef.current,'fileListRef.current')
    const img=fileListRef.current?fileListRef.current[0]:[]
    // console.log(img,'img')
    setFileList([img])
  }else if(e.target.value===3){
         setFileList(fileListRef.current);
  }
}
const onFinish= async(values)=>{

  console.log(values,'values')
  const {channel_id,title,type,content}=values;

  const params={
    channel_id,
    title,
    type,
    content,
    cover:{
        type:type,
         images:fileList.map(item=>item.url)
    }
  }
  if(id){
    await  http.put(`/mp/articles/${id}?draft=false`,params)
  }else{
    const res=await  http.post('/mp/articles?draft=false',params)
    console.log(res,'res---------')
    if(res.message==='OK'){
      message.success('success-发布成功');
      navigate('/article',{replace:true})
    }


  }


}
useEffect(()=>{
    const loadDetail=async ()=>{
      if(id){
        const res=await http.get(`/mp/articles/${id}`)
        console.log(res,'detail')
        formRef.current.setFieldsValue({...res.data,type:res.data.cover.type})
        setFileList(res.data.cover.images.map(url=>{
           return {
              url:url,

           }
        }))
        fileListRef.current=res.data.cover.images.map(url=>{
          return {
            url:url,
          }
        })

      }
    }
  loadDetail()
  // console.log(formRef.current,'formRef.current')
},[id])
  return (
    <div className="publish" >
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id?'编辑文章':'发布文章'}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
            ref={formRef}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 ,content:'this is 富文本bianjiqi'}}
          onFinish={onFinish}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {
                channelStore.channelList.map(item=><Option value={item.id} key={item.id}>{item.name}</Option>)
              }
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={radioChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount>0&&(
              <Upload
              name="image"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList
              action="http://geek.itheima.net/v1_0/upload"
              onChange={onUploadChange}
              maxCount={ imgCount }
              multiple={ imgCount > 1}
              fileList={fileList}
            >
              <div style={{ marginTop: 8 }}>
                <PlusOutlined />
              </div>
            </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {id?"编辑":'发布'}文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default observer(Publish)